<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件
use Firebase\JWT\JWT;
use think\facade\Config;


header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,X-Token");
header('Access-Control-Allow-Methods: GET, POST, PUT');
function getJson($code, $msg = "", $data)
{
    $result = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
    //输出json
    return json($result);
}

//  派发token
function getJwt($uid)
{
    $key = Config::get('test.keys');
    $token = [
        "iat" => time(), //签发时间
        "nbf" => time() + 5, //在什么时候jwt开始生效  （这里表示生成5秒后才生效）
        "exp" => time() + 3600, //token 过期时间
        "uid" => $uid   //记录的uid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
    ];
    $jwt = JWT::encode($token, $key, 'HS256');
    return ['token' => $jwt];
}

//  获取Token信息；
function checkJwt()
{
    $jwt = Request::header('token');
    $key = Config::get('test.keys');
    $time = date("Y-m-d H:i:s", time());
//    $info = JWT::decode($jwt, $key, ["HS256"]); //解密jwt
    try {
        $info = JWT::decode($jwt, $key, ["HS256"]);//解密签名token
        return json($info);
    } catch (\Exception $exception) { //如果解密失败，或者超过有效期则die
        return getJson('40001','token异常，请重新登录',$time);
    }
}

